package com.hulk.dryad.persistence.handler;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.userdetails.User;
import org.springframework.util.ClassUtils;

import java.time.LocalDateTime;

/**
 * @author hulk
 * @date 2019/10/29
 */
@Slf4j
public class CommonMetaObjectHandler implements MetaObjectHandler {

    /**
     * 创建时间
     */
    private static final String CREATED_TIME = "createdTime";
    /**
     * 修改时间
     */
    private static final String UPDATED_TIME = "updatedTime";
    /**
     * 创建者ID
     */
    private static final String CREATED_BY = "createdBy";
    /**
     * 修改者ID
     */
    private static final String UPDATED_BY = "updatedBy";
    /**
     * 乐观锁字段
     */
    public static final String REVERSION = "reversion";



    @Override
    public void insertFill(MetaObject metaObject) {
		log.debug("mybatis plus start insert fill ....");
		LocalDateTime now = LocalDateTime.now();
		String userName = null;
		User userinfo = SecurityUtils.getUser();
		if(userinfo!= null){
			userName = userinfo.getUsername();
		}
		userName = StrUtil.isEmpty(userName)? CommonConstants.DEFUAULT_CREATER:userName;
		fillValIfNullByName(CREATED_TIME, now, metaObject);
		fillValIfNullByName(CREATED_BY, userName, metaObject);
		fillValIfNullByName(REVERSION, 0L, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
		log.info("mybatis plus start update fill ....");
		String userName = null;
		User userinfo = SecurityUtils.getUser();
		if(userinfo!= null){
			userName = userinfo.getUsername();
		}
		userName = StrUtil.isEmpty(userName)? CommonConstants.DEFUAULT_UPDATE:userName;
		fillValIfNullByName(UPDATED_TIME, LocalDateTime.now(), metaObject);
		fillValIfNullByName(UPDATED_BY, userName, metaObject);

    }

	/**
	 * 填充值，先判断是否有手动设置，优先手动设置的值，例如：job必须手动设置
	 *
	 * @param fieldName  属性名
	 * @param fieldVal   属性值
	 * @param metaObject MetaObject
	 */
	private static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject) {
		// 1. 没有 get 方法
		if (!metaObject.hasSetter(fieldName)) {
			return;
		}
		// 2. 如果用户有手动设置的值
		Object userSetValue = metaObject.getValue(fieldName);
		if (ObjectUtil.isNotEmpty(userSetValue)) {
			return;
		}
		// 3. field 类型相同时设置
		Class<?> getterType = metaObject.getGetterType(fieldName);
		if (ClassUtils.isAssignableValue(getterType, fieldVal)) {
			metaObject.setValue(fieldName, fieldVal);
		}
	}

}
